import axios from 'axios'
import useTokenStore from '../stores/token'
import { ElLoading } from 'element-plus'
import config from '../config'
import notification from './notification'
import router from '../router'

const baseURL = config.baseURL

var loadingInstance = null

const service = axios.create({ baseURL })

service.interceptors.request.use(config => {
  const { token } = useTokenStore();
  if (token) {
      config.headers.token = token;
  }
  return config;
});

service.interceptors.response.use(resp => {
  if(resp==null) {
    return false
  }

  const { data, errmsg, errno } = resp.data;
  if (errno === 0) {
      if (errmsg != '') {
        notification({
              message: errmsg,
              type: 'success',
          })
      }
      return data || true;
  }
  if (errmsg != '') {
    notification({
          message: errmsg,
          type: 'error',
      })
  }
  if (errno === 2) {
      router.push('/')
  }
  return false;

}, error => {
  if (error.response && error.response.status === 401) {
    notification({
          message: '未授权，请重新登录',
          type: 'error',
      });
      router.push('/login');
      return Promise.reject(error);
  }
  notification({
      message: '请求失败',
      type: 'error',
  });
  return Promise.reject(error);
})

export default service